<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button @click="active = 'Child'">btn1</button>
      <button @click="active = 'Child2'">btn2</button>
      <button @click="active = 'Child3'">btn3</button>

      <!-- <child v-if="active === 1"></child>
      <child2 v-if="active === 2"></child2>
      <child3 v-if="active === 3"></child3> -->

      <!-- 动态组件 -->
      <!-- is属性要写字符串，组件名称的字符串 -->
      <!-- 在使用动态组件的时候，显示和隐藏组件的时候，会去加载和销毁组件的 -->

      <!-- keep-alive标签表示缓存组件 -->
      <!-- 当组件切走的时候，不会销毁和重新创建 -->
      <keep-alive>
        <component :is="active"></component>
      </keep-alive>

      <!-- 不要将tr元素或者option元素作为组件的根元素 -->
      <!-- <select name="" id="">
        <child-option></child-option>
      </select> -->
    </div>

    <script src="./lib/Vue3.js"></script>
    <script>
      const { createApp } = Vue;

      const ChildOption = {
        template: `
          <option>男</option>
        `,
      };

      const Child = {
        template: `
          <div>child子组件1</div>
        `,
      };

      let timer;
      const Child2 = {
        data() {
          return {
            count: 1,
          };
        },
        template: `
          <div>child子组件2 - {{ count }}</div>
        `,
        mounted() {
          console.log("child2组件 挂载了");
          // timer = setInterval(() => {
          //   this.count++;
          // }, 1000);
        },
        beforeUnmount() {
          console.log("child2组件 卸载了");
          clearInterval(timer);
        },
        // 必须要使用<keep-alive>之后，才能生效
        // activated是在缓存组件被激活时调用
        activated() {
          console.log("child2组件 被重新激活了");
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        // deactivated是在缓存组件被失活时调用
        deactivated() {
          console.log("child2组件 被暂时隐藏了");
          clearInterval(timer);
        },
      };

      const Child3 = {
        template: `
          <div>child子组件3</div>
        `,
      };

      createApp({
        data() {
          return {
            active: "Child",
          };
        },
        components: {
          Child,
          Child2,
          Child3,
          ChildOption,
        },
      }).mount("#app");
    </script>
  </body>
</html>
